<?php

namespace App\Listeners;

use App\Events\BindMobile;
use App\Service\CouponService;
use App\Service\MiniProgramService;
use App\Service\Sms;

class BindMobileSendCoupon
{
    public $couponService;

    public $miniProgramService;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(CouponService $couponService, MiniProgramService $miniProgramService)
    {
        $this->couponService = $couponService;
        $this->miniProgramService = $miniProgramService;
    }

    /**
     * 绑定手机号送优惠券
     *
     * @param BindMobile $event
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function handle(BindMobile $event)
    {
        if(app()->environment() == 'dev') return;
        $user = $event->user;
        // 获取绑定手机号送优惠券的礼包
        $coupon = $this->couponService->getBindMobileCoupon();

        if($coupon->isNotEmpty()) {
            $title = [];

            foreach ($coupon as $value) {


                $res = $this->couponService->giveCouponToUser($value, $user->id);

                if ($res) {
                    $title[] = $value->title;

                    if($event->formId) {
                        $this->miniProgramService->sendCouponReceive($value, $res,$event->formId);
                    }
                }

            }

            if(!$event->formId && !empty($res))
            {
                // 发送短信
                $sms = new Sms();
                $sms->sendSmsNotice($user->phone,'bindMobileNotice',[
                    'name' => implode(',',$title)
                ]);
            }
        };
    }
}
